package cn.zhf.shop.service.impl;

import cn.zhf.shop.utils.Schedule;
import cn.zhf.shop.entity.*;
import cn.zhf.shop.mapper.ChinapayMapper;
import cn.zhf.shop.mapper.OrdersMapper;
import cn.zhf.shop.mapper.ShoppingOrderMapper;
import cn.zhf.shop.service.PayService;
import cn.zhf.shop.utils.PayUtil;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

@Component
public class PayServiceImpl implements PayService {
    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private ChinapayMapper chinapayMapper;

    @Resource
    private ShoppingOrderMapper shoppingOrderMapper;

    @Override
    public Message pay(String orderId, String orderType, int periodization, String cardId) throws UnsupportedEncodingException {
        String OrderAmt ="";                                        //支付金额
        BigDecimal money = new BigDecimal(0);                   //计算金额用
        if("0".equals(orderType)){
            ShoppingOrder shoppingOrder =shoppingOrderMapper.selectByPrimaryKey(orderId);
            String[] order = shoppingOrder.getOrderId().split(";");
            for(int i=0;i<order.length;i++){
                Orders orders = ordersMapper.selectByPrimaryKey(order[i]);
                money = money.add(orders.getTotalPrice());
            }
            OrderAmt = Integer.toString(money.intValue());
        }else{
            Orders orders = ordersMapper.selectByPrimaryKey(orderId);   //查找订单
            OrderAmt = Integer.toString(orders.getTotalPrice().intValue());
        }
        JSONObject order = new JSONObject();
        String timestamp = PayUtil.getTimestamp();
        String nonce = PayUtil.getNonce();
        order.put("authorization","OPEN-FORM-PARAM");
        order.put("appId", PayUtil.APPID);
        order.put("timestamp", timestamp);
        order.put("nonce", nonce);
        /*-----------------------------内容-------------------------------*/
        JSONObject content = new JSONObject();
        content.put("requestTimestamp", PayUtil.getTime());
        content.put("merOrderId", "136L"+orderId);
//        content.put("limitCreditCard", true);
        content.put("mid", PayUtil.MID);
        content.put("tid", PayUtil.TID);
        if(periodization == 0 ){
            if (cardId != null){
                content.put("bankCardNo", Base64.getEncoder().encodeToString(cardId.getBytes()));
            }
        }else if (periodization == 1){
            content.put("mid", ""+PayUtil.MID);
            content.put("tid", ""+PayUtil.TID);
            content.put("instalFlag", true);
            content.put("bankCardNo", Base64.getEncoder().encodeToString(cardId.getBytes()));
            content.put("installmentNumber", 3);
            content.put("mchntInstalRatio", 4.5);
            content.put("mchntDiscountRatio", 0);
        }else if (periodization == 2){
            content.put("mid", ""+PayUtil.MID);
            content.put("tid", PayUtil.TID);
            content.put("instalFlag", true);
            content.put("bankCardNo", Base64.getEncoder().encodeToString(cardId.getBytes()));
            content.put("installmentNumber", 6);
            content.put("mchntInstalRatio", 5.6);
            content.put("mchntDiscountRatio", 0);
        }else if (periodization == 3){
            content.put("mid", PayUtil.MID);
            content.put("tid", PayUtil.TID);
            content.put("instalFlag", true);
            content.put("bankCardNo", Base64.getEncoder().encodeToString(cardId.getBytes()));
            content.put("installmentNumber", 12);
            content.put("mchntInstalRatio", 7.8);
            content.put("mchntDiscountRatio", 0);
        }else if (periodization == 4){
            content.put("mid", PayUtil.MID);
            content.put("tid", PayUtil.TID);
            content.put("instalFlag", true);
            content.put("bankCardNo", Base64.getEncoder().encodeToString(cardId.getBytes()));
            content.put("installmentNumber", 24);
            content.put("mchntInstalRatio", 13.5);
            content.put("mchntDiscountRatio", 0);
        }
        content.put("instMid", "H5DEFAULT");
        content.put("attachedData", orderType);
        content.put("totalAmount", OrderAmt);
        content.put("notifyUrl", "https://qiudaokeji.cn/shop/api/pay/notify");
//        content.put("returnUrl", PayUtil.MerPageUrl);
//        content.put("sceneType","AND_WAP");
//        content.put("merAppName","智荟付");
//        content.put("merAppId","https://qiudaokeji.cn/zhihuifu/#/");

        order.put("content",  URLEncoder.encode(content.toString(),"utf-8"));
        order.put("signature", URLEncoder.encode(PayUtil.Hmac_sha256(PayUtil.APPID+timestamp+nonce+PayUtil.sha256Hex(content.toString()), PayUtil.APPKEY),"utf-8"));
//        System.out.println(order.toString()+"  "+content.toString());
        return Message.success(null).add(order);
    }

    @Override
    public Message wxpay(String orderId, String orderType) throws UnsupportedEncodingException {
        String OrderAmt ="";                                        //支付金额
        BigDecimal money = new BigDecimal(0);                   //计算金额用
        if("0".equals(orderType)){
            ShoppingOrder shoppingOrder =shoppingOrderMapper.selectByPrimaryKey(orderId);
            String[] order = shoppingOrder.getOrderId().split(";");
            for(int i=0;i<order.length;i++){
                Orders orders = ordersMapper.selectByPrimaryKey(order[i]);
                money = money.add(orders.getTotalPrice());
            }
            OrderAmt = Integer.toString(money.intValue());
        }else{
            Orders orders = ordersMapper.selectByPrimaryKey(orderId);   //查找订单
            OrderAmt = Integer.toString(orders.getTotalPrice().intValue());
        }
        JSONObject order = new JSONObject();
        String timestamp = PayUtil.getTimestamp();
        String nonce = PayUtil.getNonce();
        order.put("authorization","OPEN-FORM-PARAM");
        order.put("appId", PayUtil.APPID);
        order.put("timestamp", timestamp);
        order.put("nonce", nonce);
        /*-----------------------------内容-------------------------------*/
        JSONObject content = new JSONObject();
        content.put("requestTimestamp", PayUtil.getTime());
        content.put("merOrderId", "136L"+orderId);
        content.put("mid", PayUtil.MID);
        content.put("tid", PayUtil.TID);
        content.put("instMid", "YUEDANDEFAULT");
        content.put("attachedData", orderType);
        content.put("totalAmount", OrderAmt);
        content.put("notifyUrl", "https://qiudaokeji.cn/shop/api/pay/notify");
        order.put("content",  URLEncoder.encode(content.toString(),"utf-8"));
        order.put("signature", URLEncoder.encode(PayUtil.Hmac_sha256(PayUtil.APPID+timestamp+nonce+PayUtil.sha256Hex(content.toString()), PayUtil.APPKEY),"utf-8"));
        return Message.success(null).add(order);
    }

    /**
     * 按照订单金额直接退款
     * @param orderid 退款的中国银联订单id
     * @return
     */
    @Override
    public Message refund(String orderid) throws UnsupportedEncodingException {

        Orders order = ordersMapper.selectByPrimaryKey(orderid);

//        SecssUtil secssUtil = new SecssUtil();                      //创建加密组件
//        secssUtil.init();                                           //初始化加密组件

        JSONObject refund = new JSONObject();
        String requestTimestamp = PayUtil.getTimestamp();
        String nonce = PayUtil.getNonce();
        refund.put("requestTimestamp", requestTimestamp);
        refund.put("merOrderId",  "136L"+orderid);
        if(order.getPayType() == 1){ //微信支付
            refund.put("instMid", "YUEDANDEFAULT");
        }else{
            refund.put("instMid", "H5DEFAULT");
        }
        refund.put("mid", PayUtil.MID);
        refund.put("tid", PayUtil.TID);
        refund.put("refundAmount", order.getTotalPrice());
        String str_header = "OPEN-ACCESS-TOKEN AccessToken="+ Schedule.getAccessToken();
        JSONObject resp = PayUtil.doPost("https://api-mop.chinaums.com/v1/netpay/refund",refund,str_header);
//        Map<String,String> refund = new LinkedHashMap<>();           //创建退款的顺序map
//        refund.put("requestTimestamp",ChinaPayUtil.MerId);
//        refund.put("MerOrderNo",ChinaPayUtil.getOrderId());
//        refund.put("TranDate",ChinaPayUtil.getCurrentTime());
//        refund.put("TranTime",ChinaPayUtil.getTranTime());
//        refund.put("OriOrderNo",orderid);
//        refund.put("OriTranDate",oriTranDate);
//        refund.put("RefundAmt",totalPrice);
//        secssUtil.sign(refund);                                      //对数据进行加密
//        System.out.println(secssUtil.getErrMsg());
//        refund.put("Signature",secssUtil.getSign());                 //签名
//        HttpResponse httpResponse =HttpChinaPayUtils.doPost(ChinaPayUtil.Refund_url,refund);
//        Map<String,String> resp=ChinaPayUtil.StrToMap(httpResponse.body());
        System.out.println(resp.toString());
        if("SUCCESS".equals(resp.get("errCode"))){
            order.setState(2);
            ordersMapper.updateByPrimaryKeySelective(order);
            System.out.println(order.toString());
            return Message.success("退款成功");
//        }else if("1003".equals(resp.get("errCode"))){
//            orders.setState(2);
//            ordersMapper.updateByPrimaryKeySelective(orders);
//            return Message.success("退款申请中");
        }else if("DUP_ORDER".equals(resp.get("errCode"))) {
            return Message.fail("重复退款");
        }else {
            Map<String,String> result = new HashMap<>();
            result.put("errCode", (String) resp.get("errCode"));
//            result.put("errMsg", (String) resp.get("errMsg"));
            return Message.fail("退款失败").add(result);
        }
//        secssUtil.verify(resp);
//        if("00".equals(secssUtil.getErrCode())){
//
//        }else{
//            return Message.fail("验签失败,请稍后再试").add(" 验 签 过 程 发 生 错 误 ， 错 误 信 息 为 -->" + secssUtil.getErrMsg());
//        }

    }

    @Override
    public void notify(String MerOrderNo, String TranDate, String OrderStatus, String InstMid, String AttachedData) {
        if("TRADE_SUCCESS".equals(OrderStatus)){

            if("1".equals(AttachedData)){
                Orders orders = ordersMapper.selectByPrimaryKey(MerOrderNo);
                orders.setState(1);
                orders.setPayTime(new Date());
                if(InstMid.equals("YUEDANDEFAULT")){
                    orders.setPayType(1);
                }else{
                    orders.setPayType(0);
                }
                ordersMapper.updateByPrimaryKeySelective(orders);
            }else if("0".equals(AttachedData)){
                ShoppingOrder shoppingOrder = shoppingOrderMapper.selectByPrimaryKey(MerOrderNo);
                shoppingOrder.setShoppingOrderStatus(1);
                if(shoppingOrderMapper.updateByPrimaryKeySelective(shoppingOrder)<0){
                    System.out.println("交易失败!!!!"+"Case By : PayServiceImpl 165 row");
                }
                String orders = shoppingOrder.getOrderId();
                String[] order = orders.split(";");
                for(int i=0;i<order.length;i++){
                    Orders orders1 = ordersMapper.selectByPrimaryKey(order[i]);
                    orders1.setState(1);
                    orders1.setPayTime(new Date());
                    if(InstMid.equals("YUEDANDEFAULT")){
                        orders1.setPayType(1);
                    }else{
                        orders1.setPayType(0);
                    }
                    ordersMapper.updateByPrimaryKeySelective(orders1);
                    Chinapay newChinapay = Chinapay.getInstance();
                    newChinapay.setOrderId(orders1.getId());
                    newChinapay.setOriOrderNo(MerOrderNo);
                    newChinapay.setOriTranDate(TranDate);
                    newChinapay.setOrderType(1);
                    chinapayMapper.insert(newChinapay);
                }
            }
        }else{
            System.out.println("交易失败!!!! code: "+OrderStatus);
        }
    }


//    @Override
//    public Message sign(String orderId,String ip,String ordertype) {
//        String OrderAmt ="";                                        //支付金额
//        BigDecimal money = new BigDecimal(0);                   //计算金额用
//        if("0".equals(ordertype)){
//            ShoppingOrder shoppingOrder =shoppingOrderMapper.selectByPrimaryKey(orderId);
//            String[] order = shoppingOrder.getOrderId().split(";");
//            for(int i=0;i<order.length;i++){
//                Orders orders = ordersMapper.selectByPrimaryKey(order[i]);
//                money = money.add(orders.getTotalPrice());
//            }
//            OrderAmt = Integer.toString(money.intValue());
//        }else{
//            Orders orders = ordersMapper.selectByPrimaryKey(orderId);   //查找订单
//            OrderAmt = Integer.toString(orders.getTotalPrice().intValue());
//        }
//
////        SecssUtil secssUtil = new SecssUtil();                      //创建加密组件
////        secssUtil.init();                                           //初始化加密组件
//        String MerOrderNo = ChinaPayUtil.getOrderId();              //记录生成的订单id
//        String TranDate=ChinaPayUtil.getCurrentTime();              //记录生成的订单日期
//        Map<String,String> order = new LinkedHashMap<>();           //创建订单的顺序map
//        order.put("Version", ChinaPayUtil.Version);                 //版本号
//        order.put("MerId",ChinaPayUtil.MerId);                      //商户号
//        order.put("MerOrderNo",MerOrderNo);                         //商户订单号
//        order.put("TranDate",TranDate);                             //商户交易日期
//        order.put("TranTime",ChinaPayUtil.getTranTime());           //商户交易时间
//        order.put("OrderAmt",OrderAmt);                             //订单金额
//        order.put("TranType","0004");                               //交易类型
//        order.put("BusiType","0001");                               //业务类型 (固定值)
//        order.put("MerPageUrl",ChinaPayUtil.MerPageUrl);            //商户前台通知地址
//        order.put("MerBgUrl",ChinaPayUtil.MerBgUrl);                //商户后台通知地址
//        order.put("RemoteAddr",ip);                                 //防钓鱼客户浏览器 IP
////        secssUtil.sign(order);                                      //对数据进行加密
////        order.put("Signature",secssUtil.getSign());                 //签名
//
//        /**
//         * 判断在存储中国银联订单唯一数据是否为空,空的化创建新的订单不空更新订单
//         */
//        if(chinapayMapper.selectByPrimaryKey(orderId)==null){
//            Chinapay chinapay = Chinapay.getInstance();
//            chinapay.setOrderId(orderId);
//            chinapay.setOriOrderNo(MerOrderNo);
//            chinapay.setOriTranDate(TranDate);
//            chinapay.setOrderType(Integer.parseInt(ordertype));
//            chinapayMapper.insert(chinapay);
//        }else{
//            Chinapay chinapay = chinapayMapper.selectByPrimaryKey(orderId);
//            chinapay.setOrderId(orderId);
//            chinapay.setOriOrderNo(MerOrderNo);
//            chinapay.setOriTranDate(TranDate);
//            chinapay.setOrderType(Integer.parseInt(ordertype));
//            if( chinapayMapper.updateByPrimaryKeySelective(chinapay)<0){
//                Message.fail("交易失败");
//            }
//        }
//        return  Message.success(null).add(order);   //返回加密后签名数据
//    }

}
